package com.bds.redis.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
 * className:Deal
 * discription:
 * author:luRuiHua
 * createTime:2019-07-23 11:31
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class Deal {

    @RequestMapping(value = "/deal",method = RequestMethod.POST)
    public Object deal( @RequestParam("file") MultipartFile file,@RequestParam("similar") String similar){
        log.info(">>>0011:"+file);
        Result ret = new Result();
        try {
            String filename = "";
            // 获得文件名：
            if (file!=null && !file.isEmpty()){
                filename =  file.getOriginalFilename();
                log.info(">>>003:"+filename+"<<<<<");
            }

            //准备允许读取的后缀
            String[] pics = { "xlsx", "xls", "XLSX", "XLS" };
            List<String> picList = Arrays.asList(pics);
            //获取文件名后缀
            String ext = filename.substring(filename.lastIndexOf(".") + 1);
            log.info("文件的后缀为："+ext);
            if (ext == null || !picList.contains(ext)) {
                ret.setCode("400");
                ret.setMsg("文件类型有误！上传失败！");
                return ret;

            } else {
                //1.获取流，从流中读
                InputStream inputStream = file.getInputStream();

                // 2.应用HUtool ExcelUtil获取ExcelReader指定输入流和sheet
                ExcelReader excelReader = ExcelUtil.getReader(inputStream, "sheet1");
                List<Map<String,Object>> read = excelReader.readAll();

                log.info("》》》》008："+read.size());
                if (read.size()==0){
                    ret.setCode("404");
                    ret.setMsg("文件中无数据！上传失败！请检查Excel文件！");
                    return ret;
                }

                ret = dealService(read,similar);


                //格式错误
                if("500".equals(ret.getCode())){
                    return ret;
                }else if("0".equals(ret.getCode())){//0是任务库错误
                    return ret;
                }

            }

        } catch (Exception e) {
            log.error("", e);
            ret.setCode(Const.FAIL);
            ret.setMsg("上传异常");
            return ret;
        }

        return ret;
    }

    /**
     * 处理业务
     * @param read
     */
    private Result dealService(List<Map<String, Object>> read,String similar) {
        Result res = new Result();
        List<String> checkKeyList = new ArrayList<>();
        Map<String,Object> checkMap = read.get(0);
        Iterator iter = checkMap.entrySet().iterator();
        String key = "";
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            key = entry.getKey() + "";
            checkKeyList.add(key);
        }
        if (!checkKeyList.contains("taobao_keyword")&&!checkKeyList.contains("tianmao_keyword")&&!checkKeyList.contains("tianmao_url")) {
            res.setCode("500");
            res.setMsg("Excel格式异常，请检查模板是否正确！上传失败！");
            return res;
        }

        List<Taobao> one = new ArrayList<>();
        List<Tianmao> two = new ArrayList<>();


        for (int i = 0; i < read.size(); i++) {
            Map<String, Object> map = read.get(i);
            log.info("成功进入读取！！！！！");
            String taobao_keyword = (map.get("taobao_keyword") + "").trim();
            String taobao_url = (map.get("taobao_url") + "").trim();
            Taobao taobao = new Taobao();
            taobao.setTaobao_keyword(taobao_keyword);
            taobao.setTaobao_url(taobao_url);
            one.add(taobao);


            String tianmao_keyword = (map.get("tianmao_keyword")+"").trim();
            String tianmao_url = (map.get("tianmao_url")+"").trim();
            Tianmao tianmao = new Tianmao();
            tianmao.setTianmao_keyword(tianmao_keyword);
            tianmao.setTianmao_url(tianmao_url);

            two.add(tianmao);
        }
        //遍历两个集合循环比较相似度

        List comper = comper(one, two,similar);
        //失败
        if (comper==null&&comper.size()==0){
            res.setCode("101");
            res.setMsg("无相似数据！");
        }
        //成功
        if (comper!=null&&comper.size()>0){
            //生成excel
            try {
                excel(comper);
                res.setCode("suc");
                res.setData("处理成功");
            } catch (Exception e){
                log.error("失败",e);
                res.setCode("900");
                res.setMsg("处理失败");
            }
        }
        return res;
    }



    /**
     * 遍历两个集合循环比较
     * @param one
     * @param two
     */
    private List<Res> comper(List<Taobao> one, List<Tianmao> two,String similar) {
        log.info("开始疯狂比对");
        List<Res> list = new ArrayList();

        float f = Float.parseFloat(similar);;
        for (Taobao taobao : one){
            String on = taobao.getTaobao_keyword();
            for (Tianmao tianmao : two){
                Res res = null;
                String tw = tianmao.getTianmao_keyword();
                float similarityRatio = Similar.getSimilarityRatio(on, tw);
                if (similarityRatio > f){
                   res = new Res();
                   res.setTaobao_keyword(on);
                   res.setTaobao_url(taobao.getTaobao_url());
                   res.setTianmao_keyword(tw);
                   res.setTianmao_url(tianmao.getTianmao_url());
                   res.setF(similarityRatio);

                   list.add(res);
                }
            }
        }
//        List<Res> resList = getReses(list);
//        System.out.println(">>>>0987:"+resList);
        return list;
    }
//    /**
//     * 在list中取出相似度最高的一条数据
//     */
//    private List<Res> getReses(List<Res> list){
//        log.info("在list中取出相似度最高的一条数据");
//        Set set = new HashSet();
//        for (int i = 0;i<list.size();i++){
//            for (int j = list.size()-1;j>i;j--){
//                Res res = list.get(i);
//                Res res1 = list.get(j);
//                String taobao_keyword = res.getTaobao_keyword();
//                String taobao_keyword1 = res1.getTaobao_keyword();
//                if (taobao_keyword.equals(taobao_keyword1)){
//                    float f = res.getF();
//                    float f1 = res1.getF();
//                    if (f>f1){
//                        set.add(res);
//                    }
//                }
//            }
//        }
//        List<Res> listTemp = new ArrayList(set);
//        return listTemp;
//    }

    private void excel(List<Res> comper) {
        log.info("开始写出。。。。");
        List<Res> rows = CollUtil.newArrayList(comper);
        //通过工具类创建writer
        ExcelWriter writer = new ExcelWriter("d:/writeTest1.xls");

        //跳过当前行，既第一行，非必须，在此演示用
//        writer.passCurrentRow();

        //合并单元格后的标题行，使用默认标题样式
        writer.merge(4, "结果集");
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        //关闭writer，释放内存
        writer.close();
    }
}
